<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="department.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="getSomeDate" />
        <!-- 树形组件 -->
        <el-tree
          ref="leftTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @node-click="checkedSon"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary">
            <router-link v-permission="'add-employee'" to="/employee/detail">添加员工</router-link>
          </el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exDeriveBtn">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :stripe="true" :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像" width="110px">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" size="small" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column width="110px" align="center" prop="username" label="姓名" />
          <el-table-column width="110px" align="center" prop="mobile" label="手机号" sortable />
          <el-table-column width="110px" align="center" prop="workNumber" label="工号" sortable />
          <el-table-column width="110px" align="center" prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column width="110px" prop="departmentName" label="部门" />
          <el-table-column width="110px" prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column width="200px" label="操作">
            <template v-slot="{row}">
              <el-button size="mini" type="text">
                <router-link :to="`/employee/detail/${row.id}`">查看</router-link>
              </el-button>
              <el-button size="mini" type="text" @click="showEmDelog(row.id)">角色</el-button>

              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delTrueOK(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :page-size="department.pagesize"
            :current-page="department.page"
            :total="total"
            @current-change="changePage"
          />
        </el-row>

      </div>
    </div>
    <ShowDelog :show-excel-dialog.sync="showExcelDialog" />
    <!-- 权限分配弹出层 -->
    <el-dialog title="分配角色" :visible="showEmDialog" @close="closeEmDelog">
      <!-- 可选框列表 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in checkList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" type="primary" @click="sendEmployee">确定</el-button>
          <el-button size="small" @click="closeEmDelog">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { transListToTreeData } from '@/utils/auth'
import { getAllDepartment } from '@/api/department'
import { getEmployeeList, exDeriveBtn, delEmployee, getEmployList, getById, sendEmployee } from '@/api/employee'
import FileSaver from 'file-saver'
import ShowDelog from './components/showDelog'

export default {
    name: 'Employee',
    components: {
        ShowDelog
    },
    data() {
        return {
            depts: [], // 组织数据
            defaultProps: {
                label: 'name',
                children: 'children'
            },
            department: {
                departmentId: null, // 左树选中高亮,用于保存当前选中的id
                page: 1, // 当前页
                pagesize: 5, // 每页数
                keyword: ''
            },
            total: 0, // 总页码
            // 条件获取数据
            list: [],
            // 文件上传的弹出层
            showExcelDialog: false,
            // 可选列表组
            checkList: [],
            roleIds: [],
            // 权限分配弹出层
            showEmDialog: false,
            userId: null
        }
    },
    created() {
        this.getDepartment()
    },
    methods: {
        // 修改角色权限
        async sendEmployee() {
            await sendEmployee({
                'id': this.userId,
                'roleIds': this.roleIds
            })
            this.$message.success('修改成功')
            // 关闭弹框
            this.closeEmDelog()
        },

        // 角色权限列表
        async showEmDelog(id) {
            this.checkList = await getEmployList()
            // 获取员工的权限
            let user = await getById(id)
            this.roleIds = user.roleIds
            // 角色的id要保存下来
            this.userId = user.id
            // 打开弹层
            this.showEmDialog = true
        },
        // 关闭权限列表
        closeEmDelog() {
            this.showEmDialog = false
            this.roleIds = []
        },
        async delTrueOK(id) {
            // 调用接口，删除id
            await delEmployee(id)
            this.$message.success('删除成功')
            // 判定是否是最后一条数据
            if (this.list.length === 1 && this.department.page > 1) {
                // 页码 -1
                this.department.page--
            }
            // 刷新数据
            this.getEmployeeList()
        },
        // ex文件导出
        async exDeriveBtn() {
            // 直接调用对应接口
            this.$message.success('导出成功！')
            // let res = await exDeriveBtn()
            // // res 是二进制流，使用file-saver转换下载
            // FileSaver.saveAs(res, '员工列表.xlsx')
        },
        async getDepartment() {
            // 调用工具函数，将列表转化成树形
            this.depts = transListToTreeData(await getAllDepartment(), 0)

            // 让当前选中的项高亮
            this.department.departmentId = this.depts[0].id
            this.$nextTick(() => {
                // 让初始的第一个元素被选中
                this.$refs.leftTree.setCurrentKey(this.department.departmentId)
            })
            // 初始数据
            this.getEmployeeList()
        },
        // 被选中，保存其节点的id
        checkedSon(node) {
            // 当前选中的节点数据对象
            this.department.departmentId = node.id
            // 把页码设置成第一页
            this.department.page = 1
            this.getEmployeeList()
        },
        // 按照条件获取对应数据
        async getEmployeeList() {
            let { rows, total } = await getEmployeeList(this.department)
            this.list = rows
            this.total = total
        },
        // 点击页码改变
        changePage(page) {
            this.department.page = page
            this.getEmployeeList()
        },
        // 模糊搜索
        getSomeDate() {
            clearTimeout(this.timee)
            // 防抖
            this.timee = setTimeout(() => {
                // 把页码设置成第一页
                this.department.page = 1
                this.getEmployeeList()
            }, 300)
        }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
